//
//  ShareView.m
//  华康通
//
//  Created by 雷雨 on 16/11/21.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "ShareView.h"

#define JJU ((UISCREENWEITH - (55*4))/5)
#define JJULabel (UISCREENWEITH/4)

#define TTJJU ((UISCREENWEITH - (55*3))/4)
#define TTJJULabel (UISCREENWEITH/3)

#define TJJU ((UISCREENWEITH - (55*2))/3)
#define TJJULabel (UISCREENWEITH/2)

@interface ShareView()



@end

@implementation ShareView


- (UIView*)backView
{
    if (!_backView)
    {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT)];
        _backView.alpha = 0.5;
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapForView:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [_backView addGestureRecognizer:tap];
        _backView.backgroundColor = YYColor;
    }
    return _backView;
}

//单机手势
- (void)tapForView:(UITapGestureRecognizer*)gr
{
    [self deleteViews];
}

//移除弹出视图
- (void)deleteViews
{
    [self.backView removeFromSuperview];
    [self removeFromSuperview];
}

- (NSArray*)buttonImages
{
    if (!_buttonImages)
    {
        _buttonImages = @[@"qqfriend",@"qqzone",@"wxfriend",@"wxzone"];
    }
    return _buttonImages;
}

//增加一个短信分享
- (NSArray*)threeButtonImages
{
    if (!_threeButtonImages)
    {
        _threeButtonImages = @[@"dx",@"qqfriend",@"wxfriend"];
    }
    return _threeButtonImages;
}

- (NSArray*)twoButtonImages
{
    if (!_twoButtonImages)
    {
        _twoButtonImages = @[@"qqfriend",@"wxfriend"];
    }
    return _twoButtonImages;
}

- (NSArray*)labelTitles
{
    if (!_labelTitles)
    {
        _labelTitles = @[@"QQ好友",@"QQ空间",@"微信好友",@"朋友圈"];
    }
    return _labelTitles;
}

- (NSArray*)threeLabelTitles
{
    if (!_threeLabelTitles)
    {
        _threeLabelTitles = @[@"短信",@"QQ好友",@"微信好友"];
    }
    return _threeLabelTitles;
}

- (NSArray*)twoLabelTitles
{
    if (!_twoLabelTitles)
    {
        _twoLabelTitles = @[@"QQ好友",@"微信好友"];
    }
    return _twoLabelTitles;
}


- (id)initWithFrame:(CGRect)frame withIndex:(NSInteger)index
{
    if (self = [super initWithFrame:frame])
    {
        //创建分享图标
        self.backgroundColor = FFFFFFColor;
        [self creatLabel];
        if (index == 0)
        {
            //qq好友、微信朋友圈
            [self creatTwoButtonsAndLabels];
        }
        else if (index == 2)
        {
            //短信、qq好友、微信朋友
            [self creatThreeButtonsAndLabels];
        }
        else
        {
            //微信、微信朋友圈、qq、qq空间
            [self creatALLButtonsAndLabels];
        }
    }
    return self;
}

//- (id)initWithFrame:(CGRect)frame
//{
//    if (self = [super initWithFrame:frame])
//    {
//        //创建分享图标
//        self.backgroundColor = FFFFFFColor;
//        [self creatLabel];
//        [self creatALLButtonsAndLabels];
//    }
//    return self;
//}

//创建立即分享
- (void)creatLabel
{
    self.topLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 5, 80, 20)];
    self.topLabel.text = @"分享到";
    self.topLabel.textColor = YYColor;
    self.topLabel.font = SetFont(15.0);
    self.topLabel.textAlignment = NSTextAlignmentLeft;
    [self addSubview:self.topLabel];
}

//创建4个图标
- (void)creatALLButtonsAndLabels
{
    NSMutableArray* arr = [NSMutableArray array];
    for (int i = 0; i < self.buttonImages.count; i++)
    {
        UIButton* button = [[UIButton alloc]init];
        button.frame = CGRectMake(((JJU + 55) * i) + JJU, 35, 55, 55);
        button.tag = i;
        [button setImage:LoadImage(self.buttonImages[i]] forState:UIControlStateNormal);
        [button addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [arr addObject:button];
        UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(((JJU + 55) * i) + JJU, 100, 55, 15)];
        label.text = self.labelTitles[i];
        label.textColor = YYColor;
        label.font = SetFont(12.0);
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
    }
    self.buttons = [arr copy];
}

//创建3个图标
- (void)creatThreeButtonsAndLabels
{
    NSMutableArray* arr = [NSMutableArray array];
    for (int i = 0; i < self.threeButtonImages.count; i++)
    {
        UIButton* button = [[UIButton alloc]init];
        button.frame = CGRectMake(((TTJJU + 55) * i) + TTJJU, 35, 55, 55);
        button.tag = i;
        [button setImage:LoadImage(self.threeButtonImages[i]] forState:UIControlStateNormal);
        [button addTarget:self action:@selector(threeOtherShare:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [arr addObject:button];
        UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(((TTJJU + 55) * i) + TTJJU, 100, 55, 15)];
        label.text = self.threeLabelTitles[i];
        label.textColor = YYColor;
        label.font = SetFont(12.0);
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
    }
    self.buttons = [arr copy];
}

//创建2个图标
- (void)creatTwoButtonsAndLabels
{
    NSMutableArray* arr = [NSMutableArray array];
    for (int i = 0; i < self.twoButtonImages.count; i++)
    {
        UIButton* button = [[UIButton alloc]init];
        button.frame = CGRectMake(((TJJU + 55) * i) + TJJU, 35, 55, 55);
        button.tag = i;
        [button setImage:LoadImage(self.twoButtonImages[i]] forState:UIControlStateNormal);
        [button addTarget:self action:@selector(otherShare:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [arr addObject:button];
        UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(((TJJU + 55) * i) + TJJU, 100, 55, 15)];
        label.text = self.twoLabelTitles[i];
        label.textColor = YYColor;
        label.font = SetFont(12.0);
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
    }
    self.buttons = [arr copy];
}

//分享
- (void)share:(UIButton*)sender
{
    ////处理字符串 得到分享标题、内容、url、图片
    [self getAllString];
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (sender.tag)
        {
            case 0:
            {
                
                [self Share1];
            }
                break;
            case 1:
            {
                [self Share2];
            }
                break;
            case 2:
            {
                [self Share3];
            }
                break;
            case 3:
            {
                [self Share4];
            }
                break;
            default:
                break;
        }
        [self deleteViews];
    });
    NSLog(@"分享button tag = %ld",(long)sender.tag);
}

//3个按钮时的分享方法
- (void)threeOtherShare:(UIButton*)sender
{
    ////处理字符串 得到分享标题、内容、url、图片
    [self getAllString];
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (sender.tag)
        {
            case 0:
            {
                [self pushAlertView];
            }
                break;
            case 1:
            {
                [self Share1];
            }
                break;
            case 2:
            {
                [self Share3];
            }
                break;
            default:
                break;
        }
        [self deleteViews];
    });
    NSLog(@"分享button tag = %ld",(long)sender.tag);
}

//2个按钮时的分享方法
- (void)otherShare:(UIButton*)sender
{
    ////处理字符串 得到分享标题、内容、url、图片
    [self getAllString];
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (sender.tag)
        {
            case 0:
            {
                [self Share1];
            }
                break;
            case 1:
            {
                [self Share3];
            }
                break;
            default:
                break;
        }
        [self deleteViews];
    });
    NSLog(@"分享button tag = %ld",(long)sender.tag);
}

//创建一个弹出视图
- (void)pushAlertView
{
    self.myBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, UISCREENHEIGHT)];
    self.myBackView.backgroundColor = YYColor;
    self.myBackView.alpha = 0.7;
    [[UIApplication sharedApplication].keyWindow addSubview:self.myBackView];
    
    //创建弹出视图
    self.shareAlertView = [ShareAlertView view];
    self.shareAlertView.lineView.layer.cornerRadius = 4.0;
    self.shareAlertView.lineView.layer.masksToBounds = YES;
    self.shareAlertView.lineView.layer.borderWidth = 1.0;
    self.shareAlertView.lineView.layer.borderColor = F0F0F0Color.CGColor;
    self.shareAlertView.frame = CGRectMake((UISCREENWEITH - 270)/2, (UISCREENHEIGHT - 316)/2, 270, 316);
    self.shareAlertView.backgroundColor = FFFFFFColor;
    self.shareAlertView.layer.cornerRadius = 10.0;
    self.shareAlertView.layer.masksToBounds = YES;
    
    self.shareAlertView.postBlock = ^(NSString * _Nonnull text) {
        NSLog(@"text = %@",text);
        [self goPostPhoneWithText:text];
    };
    self.shareAlertView.closeBlock = ^() {
        [self dismissView];
    };
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.shareAlertView];
}

- (void)dismissView
{
    [self.shareAlertView removeFromSuperview];
    [self.myBackView removeFromSuperview];
    self.shareAlertView = nil;
    self.myBackView = nil;
}

//向后台发送请求，post手机号码
- (void)goPostPhoneWithText:(NSString*)text
{
    if (![self.shareAlertView.textField.text isEqualToString:@""])
    {
        //验证是否为手机号码
        if ([ExamineTool verityPhoneWithString:self.shareAlertView.textField.text])
        {
            //手机号码输入框
            [self dismissView];
//            [self postMessageForSevenWithPhoneNumber:self.shareAlertView.textField.text];
        }
        else
        {
            XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
            [statusBar showStatusMessage:@"手机号码格式错误"];
        }
    }
    else
    {
        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
        [statusBar showStatusMessage:@"还未输入手机号码"];
    }
}

//发送短信，需要与后台进行交互
- (void)postMessageForSevenWithPhoneNumber:(NSString*)number
{
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"getPictures",
                           @"requestObject":@{
                                   @"pictureType": @"home_banner",
                                   @"platform":@"2",
                                   @"pageParams":@{
                                           @"currentPage": @"1",
                                           @"pageSize": @"20",
                                           @"queryAll": @NO
                                           }
                                   }
                           };
    NSLog(@"网络加载首页广告图片json = %@",json);
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self postMessageForSevenWithURL:url withParam:json];
}

- (void)postMessageForSevenWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"获取手机号码返回json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"])
                {
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
                            [statusBar showStatusMessage:@"发送成功"];
                        });
                    });
                    
                }
                else
                {
                    [self showError];
                }
            }
            else
            {
                [self showError];
            }
        } failure:^(NSError *error) {
            [self showError];
        }];
        
    } failure:^{
        //展示广告图
        NSLog(@"检测到设备无网络连接！！！");
    }];
}

- (void)showError
{
    dispatch_async(dispatch_get_main_queue(), ^{
        XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
        [statusBar showStatusMessage:@"发送失败"];
    });
    
}

//分享到qq空间
- (void)Share2
{
    OSMessage* msg= [[OSMessage alloc]init];
    msg.title=self.title;
    if (![self.imageURL isEqualToString:@""])
    {
        if ([self.imageURL rangeOfString:HTTP].location != NSNotFound)
        {
            NSURL *url = [NSURL URLWithString:self.imageURL];
            msg.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
            msg.image = [UIImage imageWithData:[OpenShare dataWithImage:msg.image scale:CGSizeMake(100, 100)]];
        }
        else
        {
            msg.image = LoadImage(self.imageURL);
        }
    }
    else
    {
        msg.image = LoadImage(@"icon1.png");
    }
    msg.desc=self.content;
    msg.link = self.url;
    [OpenShare shareToQQZone:msg Success:^(OSMessage *message) {
        //分享qq空间成功要写的代码
        [self finishShared];
        NSLog(@".........................分享qq空间成功");
    } Fail:^(OSMessage *message, NSError *error) {
        //分享qq空间失败要写的代码
        NSLog(@"分享到QQ空间失败:%@\n%@",msg,error);
    }];
}
//分享到qq好友
- (void)Share1
{
    OSMessage* msg = [[OSMessage alloc]init];
    msg.title = self.title;
    if (![self.imageURL isEqualToString:@""])
    {
        if ([self.imageURL rangeOfString:HTTP].location != NSNotFound)
        {
            NSURL *url = [NSURL URLWithString:self.imageURL];
            msg.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
            msg.image = [UIImage imageWithData:[OpenShare dataWithImage:msg.image scale:CGSizeMake(100, 100)]];
        }
        else
        {
            msg.image = LoadImage(self.imageURL);
        }
    }
    else
    {
        msg.image = LoadImage(@"icon1.png");
    }
    msg.desc = self.content;
    msg.link = self.url;
    [OpenShare shareToQQFriends:msg Success:^(OSMessage *message) {
        //分享qq好友成功要写的代码
        [self finishShared];
        NSLog(@".........................分享qq好友成功");
    } Fail:^(OSMessage *message, NSError *error) {
        //分享qq好友失败要写的代码
        NSLog(@"分享到QQ好友失败:%@\n%@",msg,error);
    }];
}

//分享到微信好友
- (void)Share3
{
    OSMessage* msg=[[OSMessage alloc]init];
    msg.title=self.title;
    if (![self.imageURL isEqualToString:@""])
    {
        if ([self.imageURL rangeOfString:HTTP].location != NSNotFound)
        {
            NSURL *url = [NSURL URLWithString:self.imageURL];
            msg.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
            msg.image = [UIImage imageWithData:[OpenShare dataWithImage:msg.image scale:CGSizeMake(100, 100)]];
        }
        else
        {
            msg.image = LoadImage(self.imageURL);
        }
    }
    else
    {
        msg.image = LoadImage(@"icon1.png");
    }
    msg.desc=self.content;
    msg.link = self.url;
    [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
        //分享微信好友成功要写的代码
        NSLog(@".........................分享微信好友成功");
        [self finishShared];
    } Fail:^(OSMessage *message, NSError *error) {
        //分享微信好友失败要写的代码
        NSLog(@"微信分享到会话失败：\n%@\n%@",error,message);
    }];
}

//分享到微信朋友圈
- (void)Share4
{
    OSMessage* msg=[[OSMessage alloc]init];
    msg.title=self.title;
    if (![self.imageURL isEqualToString:@""])
    {
        if ([self.imageURL rangeOfString:HTTP].location != NSNotFound)
        {
            NSURL *url = [NSURL URLWithString:self.imageURL];
            msg.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
            msg.image = [UIImage imageWithData:[OpenShare dataWithImage:msg.image scale:CGSizeMake(100, 100)]];
        }
        else
        {
            msg.image = LoadImage(self.imageURL);
        }
    }
    else
    {
        msg.image = LoadImage(@"icon1.png");
    }
    msg.desc=self.content;
    msg.link = self.url;
    [OpenShare shareToWeixinTimeline:msg Success:^(OSMessage *message) {
        //分享微信空间成功要写的代码
        NSLog(@".........................分享朋友圈成功 message = %@",message);
        [self finishShared];
    } Fail:^(OSMessage *message, NSError *error) {
        //分享微信空间失败要写的代码
        NSLog(@"微信分享到朋友圈失败：\n%@\n%@",error,message);
    }];
}

//完成分享(弹出视图)
- (void)finishShared
{
    self.hidden = NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}

//处理字符串 得到分享标题、内容、url、图片
- (void)getAllString
{
    if (self.message)
    {
        if ([self.message rangeOfString:@"!#"].location != NSNotFound)
        {
            NSArray* arr = [self.message componentsSeparatedByString:@"!#"];
            if (arr.count == 4)
            {
                self.title = arr[0];
                self.imageURL = arr[1];
                if ([arr[1] isEqualToString:@"undefined"])
                {
                    self.imageURL = @"";
                }
                self.content = arr[2];
                self.url = arr[3];
            }
        }
    }
}


@end
